#!/bin/bash
###SHELLPACK preamble salmon-bench 1.2.1
###SHELLPACK parseargBegin
###SHELLPACK parseargParam --model      SALMON_MODEL
###SHELLPACK parseargParam --processes  SALMON_PROCESSES
###SHELLPACK parseargParam --threads    SALMON_THREADS
###SHELLPACK parseargParam --iterations SALMON_ITERATIONS
###SHELLPACK parseargEnd
###SHELLPACK monitor_hooks

export CMAKE_VERSION="v3.8.2"
export BLAS_VERSION="v0.3.10"
export SCALAPACK_VERSION="2.1.0"
export XC_VERSION="4.2.1"

MPIRUN=
if [ "$SALMON_OPENMPI_VERSION" != "" ]; then
	###SHELLPACK mpi_setup_deps SALMON_OPENMPI_VERSION
	###SHELLPACK mpi_setup_env SALMON_OPENMPI_VERSION SALMON_MPI_PATH SALMON_MPI_LIBPATH SALMON_MPI_OPTS
	###SHELLPACK mpi_setup_shmem
	if [ "$SALMON_PROCESSES" -gt 1 ]; then
		MPIRUN="mpirun $SALMON_MPI_OPTS $MMTESTS_MPI_OPTS -np $SALMON_PROCESSES"
	fi
fi

rm -rf $SHELLPACK_SOURCES/salmondeps-installed
###SHELLPACK check_external_install_required cmakebuild     cmakebuild-${CMAKE_VERSION}         ${CMAKE_VERSION}
###SHELLPACK check_external_install_required blasbuild      blasbuild-${BLAS_VERSION}           ${BLAS_VERSION}
###SHELLPACK check_external_install_required scalapackbuild scalapackbuild-${SCALAPACK_VERSION} ${SCALAPACK_VERSION}
###SHELLPACK check_external_install_required xcbuild        xcbuild-${XC_VERSION}               ${XC_VERSION}

export PATH=$SHELLPACK_SOURCES/salmondeps-installed/bin:$PATH
###SHELLPACK check_install_required_continue salmon-$VERSION
###SHELLPACK init_complete

export LD_LIBRARY_PATH="$SHELLPACK_SOURCES/salmondeps-installed/$MMTESTS_LIBDIR:$LD_LIBRARY_PATH"

case $SALMON_MODEL in
bulkSi)
	INPUT_DIR=$SHELLPACK_SOURCES/salmon-$VERSION/examples/exercise_06_bulkSi_ms
	INPUT=$INPUT_DIR/Si_gs_rt_multiscale.inp
	;;
classicem)
	INPUT_DIR=$SHELLPACK_SOURCES/salmon-$VERSION/examples/exercise_07_classicEM_lr
	INPUT=$INPUT_DIR/classicEM_rt_response.inp
	;;
*)
	die "Unrecognised model $SALMON_MODEL"
esac

export OMP_NUM_THREADS=$SALMON_THREADS
BENCH_CMD="$MPIRUN $SHELLPACK_SOURCES/salmon-$VERSION-installed/bin/salmon.cpu"
log_runtime "OMP_NUM_THREADS=$SALMON_THREADS"
log_runtime "OMP_PLACES=$OMP_PLACES"
log_runtime "OMP_PROC_BIND=$OMP_PROC_BIND"
log_cmd "$BENCH_CMD"
log_linkages $SHELLPACK_SOURCES/salmon-$VERSION-installed/bin/salmon.cpu
echo $SALMON_PROCESSES : $SALMON_THREADS > $LOGDIR_RESULTS/scaling-parameters
cd $INPUT_DIR || die "Failed to change to $INPUT_DIR"
monitor_pre_hook $LOGDIR_RESULTS $SALMON_MODEL
###SHELLPACK iteration_begin $SALMON_ITERATIONS
	echo Executing iteration $ITERATION/$SALMON_ITERATIONS
	eval $TIME_CMD -o $LOGDIR_RESULTS/salmon-time.$ITERATION	\
		$BENCH_CMD < $INPUT > $LOGDIR_RESULTS/salmon-log.$ITERATION
	RET=$?
	gzip $LOGDIR_RESULTS/salmon-log.$ITERATION
	if [ $RET -ne 0 ]; then
		die "Failed to execute salmon"
	fi
###SHELLPACK iteration_end
monitor_post_hook $LOGDIR_RESULTS $SALMON_MODEL

exit $SHELLPACK_SUCCESS
